from main import basedir

import platform
from flask import request, make_response, send_file, session
import time, os
from main.code import *
from main.utils import InterfaceHelper, RequestHelper, FileHelper, snowflake, ImageHelper
from main.dbs.lab import *
from main.dbs.user import *
from main.dbs.common import *
from flask_restplus import Api, Resource, fields
from . import api, check_cookie, set_session, check_admin_cookie

# 定义命名空间
ns = api.namespace('lab', description='Lab api')

lab_model = api.model('LabModel', {
    'id': fields.Integer(readOnly=True, description='用户id'),
    'borrow_status': fields.Integer(description='状态'),
    'name': fields.String(),
    'image': fields.String(),
    'status': fields.Integer(description='状态'),
    'create_time': fields.DateTime(description='时间')
})

labSubscribe_model = api.model('LabSubscribeModel', {
    'id': fields.Integer(readOnly=True, description='用户id'),
    'lab_id': fields.Integer(description='用户id'),
    'subscribe_id': fields.Integer(description='用户id'),
    'start_time': fields.DateTime(),
    'status': fields.Integer(description='状态'),
    'create_time': fields.DateTime(description='时间')
})


@ns.route('')
class LabApi(Resource):

    @ns.expect(lab_model)
    def post(self):
        '''添加实验室'''
        user_id = check_cookie()
        parameters = RequestHelper.formToDict(request)
        lab = JSONHelper.dictToObj(parameters, Lab)
        if insert(lab):
            return success()
        return fail()


@ns.route('/list')
class LabListApi(Resource):

    @ns.param('')
    def get(self):
        '''获得列表'''
        user_id = check_cookie()
        parameters = RequestHelper.formToDict(request)
        data = []
        for i in query_lab_list():
            i.count = count_lab_usedNum(i.id)
            data.append(i.to_json())
        return success(data)


@ns.route('/subscribe')
class LabSubscribeApi(Resource):

    @ns.expect(labSubscribe_model)
    def post(self):
        '''预约实验室'''
        user_id = check_cookie()
        parameters = RequestHelper.formToDict(request)
        ls = query_labSubscribe_by_userId_labId(user_id, parameters['lab_id'])
        if ls:
            if ls.examine_status == 0:
                return fail('你已经预约')
            if ls.examine_status == 1:
                return fail('你正在使用')
        labSubscribe = JSONHelper.dictToObj(parameters, LabSubscribe)
        labSubscribe.subscribe_id = user_id
        if insert(labSubscribe):
            lab = query_lab_by_id(parameters['lab_id'])
            lab.borrow_status = 1
            update(lab)
            return success()
        return fail()

    @ns.param('id')
    @ns.param('examine_status', '1-used 2-reject')
    def put(self):
        '''审批实验室'''
        user_id = check_cookie()
        parameters = RequestHelper.formToDict(request)
        ls = query_labSubscribe_by_id(parameters['id'])
        ls.examine_status = parameters['examine_status']
        lab = query_lab_by_id(ls.lab_id)
        print(parameters['examine_status'])
        if int(parameters['examine_status']) == 1:
            lab.borrow_status = 2
        else:
            lab.borrow_status = 0
        if update(ls):
            update(lab)
            return success()
        return fail()


@ns.route('/borrow/list')
class LabBorrowListApi(Resource):

    @ns.param('subscribe_id')
    @ns.param('examine_status', '0')
    @ns.param('date', '0')
    def get(self):
        '''获得列表'''
        user_id = check_cookie()
        parameters = RequestHelper.formToDict(request)
        data = []
        for i in query_labSubscribe_list(parameters):
            i.subscribe = query_user_by_id(i.subscribe_id).to_json()
            if i.start_time:
                i.start_time = str(i.start_time)
            i.lab = query_lab_by_id(i.lab_id).to_json()
            data.append(i.to_json())
        return success(data)


@ns.route('/back')
class LabBackApi(Resource):

    @ns.param('id')
    def post(self):
        '''归还实验室'''
        user_id = check_cookie()
        parameters = RequestHelper.formToDict(request)
        ls = query_labSubscribe_by_id(parameters['id'])
        lab_id = ls.lab_id
        # if ls.examine_status == 2:
        #     return fail('实验室使用结束')
        ls.examine_status = 2
        if update(ls):
            # e = query_lab_by_id(lab_id)
            # e.borrow_status = 0
            # update(e)
            return success()
        return fail()


@ns.route('/analyze')
class LabAnalyzeApi(Resource):

    @ns.param('date')
    def get(self):
        '''获取分析数据'''
        parameters = RequestHelper.formToDict(request)
        data = {'month': query_labSubscribe_by_month(parameters['date']),
                'week': query_labSubscribe_by_week(parameters['date'])}
        return success(data)


@ns.route('/recycle')
class LabRecycleApi(Resource):

    @ns.param('id')
    def post(self):
        """实验室回收"""
        parameters = RequestHelper.formToDict(request)
        print(parameters)
        lab = query_lab_by_id(parameters['id'])
        lab.borrow_status = 0
        if update(lab):
            return success()
        return fail()
